package com.raincat.multimediapicker.utils;

import android.content.Context;
import android.database.Cursor;
import android.provider.MediaStore.Images.Media;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;

public class AlbumHelper extends Helper {
    // 专辑列表，显示用
    private List<ImageBucket> imageBucketList = new ArrayList<>();
    // 最迟的一张图片，刷新判断用
    private String lastImgPath = "";
    // 单例模式
    private static AlbumHelper instance;

    // 图片获取完毕回调
    public interface onImagesBucketListGetListener {
        void onFinish(List<ImageBucket> bucketList);
    }

    public static AlbumHelper getInstance(Context context) {
        if (instance == null) {
            instance = new AlbumHelper(context.getApplicationContext());
        }
        return instance;
    }

    private AlbumHelper(Context context) {
        init(context);
    }

    /**
     * 初始化
     */
    private void init(Context context) {
        if (cr == null) {
            cr = context.getContentResolver();
        }
    }

    /**
     * 获取最近图片(瞬间完成，不需要同步线程)
     *
     * @param count 最近的count张图片，非0
     */
    public List<ImageItem> getLatelyImage(int count) {
        List<ImageItem> TempList = new ArrayList<>();
        int index = 0;

        // 构造相册索引
        String columns[] = new String[]{Media._ID, Media.DATA, Media.DISPLAY_NAME, Media.SIZE, Media.DATE_MODIFIED};
        // 得到一个游标，时间从新到旧读取
        Cursor cur = cr.query(Media.EXTERNAL_CONTENT_URI, columns, null, null, Media.DATE_MODIFIED + " desc");
        if (cur.moveToFirst()) {
            // 获取指定列的索引
            int photoIDIndex = cur.getColumnIndexOrThrow(Media._ID);
            int photoPathIndex = cur.getColumnIndexOrThrow(Media.DATA);
            int addTime = cur.getColumnIndexOrThrow(Media.DATE_MODIFIED);
            int photoSizeIndex = cur.getColumnIndexOrThrow(Media.SIZE);
            do {
                String _id = cur.getString(photoIDIndex);
                String path = cur.getString(photoPathIndex);
                long bucketTime = cur.getLong(addTime);
                String size = cur.getString(photoSizeIndex);// 不能转int，因为有可能为null

                // 过滤小图和空图
                if (size != null && Integer.parseInt(size) > 1024 && fileIsExists(path)) {
                    ImageItem item = new ImageItem();
                    item.imageId = _id;
                    item.imagePath = path;
                    item.imageAddTime = bucketTime;
                    item.imageSize = Float.valueOf(size);
                    item.imageSuffix = path.substring((path.lastIndexOf(".") + 1));
                    TempList.add(item);

                    // 够张数就返回
                    if (++index == count) {
                        cur.close();
                        return TempList;
                    }
                }

            } while (cur.moveToNext());
        }
        // 不够100张时候的返回
        cur.close();
        return TempList;
    }

    /**
     * 获取图片集，外部调用，异步
     */
    public void getImagesBucketList(final onImagesBucketListGetListener b) {
        // 构造相册索引(异步)
        new Thread(new Runnable() {
            @Override
            public void run() {
                getImagesBucketListSync(b);
            }
        }).start();
    }

    /**
     * 检查最新一张图片的路径变化判断是否需要刷新图片列表
     *
     * @return true需要刷新
     */
    private boolean isShouldRefresh() {
        List<ImageItem> tempPath = getLatelyImage(1);
        if (tempPath.size() != 0) {
            if (tempPath.get(0).imagePath.equals(lastImgPath)) {
                lastImgPath = tempPath.get(0).imagePath;
                return false;
            } else {
                lastImgPath = tempPath.get(0).imagePath;
                return true;
            }
        } else
            return false;
    }

    /**
     * 从数据库读取图片集，同一时间只能进入一次，第二次之后直接返回数据
     */
    private synchronized void getImagesBucketListSync(final onImagesBucketListGetListener b) {
        if (!isShouldRefresh() && imageBucketList.size() != 0) {
            if (b != null)
                b.onFinish(imageBucketList);
            return;
        }

        imageBucketList.clear();
        // 哈希链表，遍历的时候会从最开始加入的数据开始读出
        LinkedHashMap<String, ImageBucket> bucketMap = new LinkedHashMap<>();

        List<ImageItem> tmpImageItemList = getLatelyImage(100);
        ImageBucket near = new ImageBucket();
        near.bucketName = "最近图片";
        near.count = tmpImageItemList.size();
        near.imageList = tmpImageItemList;
        bucketMap.put("1", near);

        String columns[] = new String[]{Media._ID, Media.BUCKET_ID, Media.DATA, Media.DISPLAY_NAME, Media.SIZE, Media.BUCKET_DISPLAY_NAME, Media.DATE_MODIFIED};
        // 得到一个游标，时间从新到旧读取
        Cursor cur = cr.query(Media.EXTERNAL_CONTENT_URI, columns, null, null, Media.DATE_MODIFIED + " desc");
        if (cur.moveToFirst()) {
            // 获取指定列的索引
            int photoIDIndex = cur.getColumnIndexOrThrow(Media._ID);
            int photoPathIndex = cur.getColumnIndexOrThrow(Media.DATA);
            int bucketDisplayNameIndex = cur.getColumnIndexOrThrow(Media.BUCKET_DISPLAY_NAME);
            int bucketIdIndex = cur.getColumnIndexOrThrow(Media.BUCKET_ID);
            int addTime = cur.getColumnIndexOrThrow(Media.DATE_MODIFIED);
            int photoSizeIndex = cur.getColumnIndexOrThrow(Media.SIZE);
            do {
                String _id = cur.getString(photoIDIndex);
                String path = cur.getString(photoPathIndex);
                String bucketName = cur.getString(bucketDisplayNameIndex);
                String bucketId = cur.getString(bucketIdIndex);
                long bucketTime = cur.getLong(addTime);
                String size = cur.getString(photoSizeIndex);

                // 文件为空或者文件太小的不保存
                if (size == null || Integer.parseInt(size) <= 1024 || !fileIsExists(path)) {
                    continue;
                }

                ImageBucket bucket;
                if (bucketMap.get(bucketId) == null) {
                    bucket = new ImageBucket();
                    bucket.bucketName = bucketName;
                    bucketMap.put(bucketId, bucket);
                } else {
                    bucket = bucketMap.get(bucketId);
                    bucket.bucketName = bucketName;
                }

                bucket.count++;
                ImageItem item = new ImageItem();
                item.imageId = _id;
                item.imagePath = path;
                item.imageAddTime = bucketTime;
                item.imageSize = Float.valueOf(size);
                item.imageSuffix = path.substring((path.lastIndexOf(".") + 1));

                bucket.imageList.add(item);
            } while (cur.moveToNext());
        }
        cur.close();
        for (ImageBucket imageBucket : bucketMap.values()) {
            Collections.addAll(imageBucketList, imageBucket);
        }
        if (b != null) {
            b.onFinish(imageBucketList);
        }
    }
}
